package com.szholly.plug.activity.interceptor.defulat;

import java.util.Date;

import org.springframework.stereotype.Component;

import com.szholly.plug.activity.interceptor.BpmHandleOptionBase;
import com.szholly.plug.activity.interceptor.BpmInterceptorRegister;
import com.szholly.plug.activity.interceptor.ICustomBpmNotice;
import com.szholly.plug.activity.interceptor.OptionInfo;
import com.szholly.plug.activity.model.BpmConfigCache;
import com.szholly.plug.activity.model.BpmConfigRow;
import com.szholly.plug.activity.model.BpmTaskConfigRow;
import com.szholly.utils.common.notice.IEmailNotice;
import com.szholly.utils.common.notice.IPhoneNotice;
import com.szholly.utils.common.notice.ISystemNotice;
import com.szholly.utils.spring.SpringBeanFactory;
import com.szholly.utils.util.DateUtils;
import com.szholly.utils.util.StringUtils;
import com.szholly.data.general.GlobalDataType;
import com.szholly.data.general.IQueryMap;
import com.szholly.data.general.QueryMap;
import com.szholly.plug.safe.entity.user.UserEntity;
import com.szholly.plug.safe.entity.user.UserService;

/**
 * 定义流程事件通知处理器
 */
@Component
public class NoticeBpmOption extends BpmHandleOptionBase {

	/**
	 * 注册拦截接口
	 */
	static {
		NoticeBpmOption interceptor = new NoticeBpmOption();
		BpmInterceptorRegister.RegDbInterceptor(interceptor);
	}

	private ISystemNotice systemNotice;
	private IEmailNotice emailNotice;
	private IPhoneNotice phoneNotice;

	private ISystemNotice getSystemNotice() {
		if (systemNotice == null) {
			systemNotice = (ISystemNotice) SpringBeanFactory
					.getBean(ISystemNotice.class);
		}
		return systemNotice;
	}

	private IEmailNotice getEmailNotice() {
		if (emailNotice == null) {
			emailNotice = (IEmailNotice) SpringBeanFactory
					.getBean(IEmailNotice.class);
		}
		return emailNotice;
	}

	private IPhoneNotice getPhoneNotice() {
		if (phoneNotice == null) {
			phoneNotice = (IPhoneNotice) SpringBeanFactory
					.getBean(IPhoneNotice.class);
		}
		return phoneNotice;
	}

	/**
	 * 流程任务操作
	 * 
	 * @param optionInfo
	 */
	@Override
	public void taskOption(OptionInfo optionInfo) {
		
		String taskId = optionInfo.TaskId;
		String taskDefinitionKey = optionInfo.TaskDefinitionKey;
		String taskAssignees = optionInfo.TaskAssignees;
		
		String[] ids = taskId.split(",");
		String[] definitionKeys = taskDefinitionKey.split(",");
		
		for(int i=0;i<ids.length;i++){
			String task = definitionKeys[i];
			String user = getTaskAssignees(taskAssignees, task);
			
			BpmConfigRow configRow =  BpmConfigCache.getConfig(optionInfo.BpmId);
			BpmTaskConfigRow configTaskRow = BpmConfigCache.getTaskConfig(optionInfo.BpmId, task);
			
			if(configTaskRow==null){
				continue;
			}
			
			// 经办
			if(!StringUtils.IsNullOrSpace(configTaskRow.getNoticeJb())
					&& configTaskRow.getNoticeJb().equals("1")
					&& !StringUtils.IsNullOrSpace(configTaskRow.getNoticeJbmb())){
				String body = configTaskRow.getNoticeJbmb();
				UserEntity to = getUser(optionInfo.TaskApplyName);
				sendMsg(optionInfo, configRow, configTaskRow, to, body);
			}
			
			// 待办
			if(!StringUtils.IsNullOrSpace(configTaskRow.getNoticeDb())
					&& configTaskRow.getNoticeDb().equals("1")
					&& !StringUtils.IsNullOrSpace(configTaskRow.getNoticeDbmb())){
				String body = configTaskRow.getNoticeDbmb();
				String[] userIds = user.split(",");
				for(String userId : userIds){
					UserEntity to = getUser(userId);
					sendMsg(optionInfo, configRow, configTaskRow, to, body);
				}
			}
			
			// 历史处理人通知
			if(!StringUtils.IsNullOrSpace(configTaskRow.getNoticeLsr())
					&& configTaskRow.getNoticeLsr().equals("1")
					&& !StringUtils.IsNullOrSpace(configTaskRow.getNoticeLsrmb())){
				String body = configTaskRow.getNoticeLsrmb();
				UserEntity to = getUser(optionInfo.TaskAssigneesId);
				sendMsg(optionInfo, configRow, configTaskRow, to, body);
			}
			
			String springName = configTaskRow.getTaskTgtz();
			if(!StringUtils.IsNullOrSpace(springName)){
				ICustomBpmNotice custom = (ICustomBpmNotice)SpringBeanFactory.getBean(springName);
				custom.taskOption(optionInfo, configRow, configTaskRow);
			}
		}
	}
	
	private UserEntity getUser(String userId){
		IQueryMap queryMap = new QueryMap();
		queryMap.getWhereMap().put(UserEntity.FIELD_USERID, userId);
		return UserService.getSingleRef().getEntity(UserEntity.class, queryMap);
	}
	
	/**
	 * 获取当前任务的审批人
	 * @param taskKey
	 * @return
	 */
	private String getTaskAssignees(String assignees, String taskKey){
		String[] taskUserList = assignees.split(":");
		// 找到当前的任务审批人
		String taskitem = "";
		for(String item : taskUserList){
			if(item.contains(taskKey)){
				taskitem = item;
				break;
			}
		}
		String[] users = taskitem.split(",");
		String workUsers = "";
		for(int i=2; i<users.length; i+=2){
			workUsers += users[i] + ",";
		}
		if(workUsers!=""){
			workUsers = workUsers.substring(0, workUsers.length()-1);
		}
		return workUsers;
	}

	private void sendMsg(OptionInfo optionInfo, BpmConfigRow configRow, 
			BpmTaskConfigRow configTaskRow, UserEntity to, String body) {
		body = body.replace("{BpmDefinitionName}", configRow.getSDefitionName()); // 工作流定义名称
		body = body.replace("{BpmGroupName}", configRow.getSGroup()); // 工作流所在分组名称
		body = body.replace("{TaskDefinitionName}", configTaskRow.getTaskName()); // 当前任务定义名称
		
		String businessFields = configRow.getBusiness();
		String business = "";
		if(!StringUtils.IsNullOrSpace(businessFields)){
			String[] fields = businessFields.split(",");
			for(String field : fields){
				String value = (String)optionInfo.BusinessRow.getValue(GlobalDataType.String, field);
				if(StringUtils.IsNullOrSpace(value)){
					business += ",";
				}else{
					business += value + ",";
				}
			}
			business = business.substring(0, business.length()-1);
		}
		body = body.replace("{TaskTitle}", business); // 流程任务的业务名称
		body = body.replace("{TaskUser}", optionInfo.TaskAssigneesName); // 流程任务的处理人
		Date nowDate = new Date();
		body = body.replace("{TaskTime}", DateUtils.convertDateTimeToString(nowDate)); // 流程任务的处理时间
		String qx = configTaskRow.getRemindersQx();
		body = body.replace("{TaskSurplusTime}", qx); // 任务时限时间(小时)
		body = body.replace("{TaskEndTime}", DateUtils.convertDateTimeToString(nowDate)); // 任务时限时间
		body = body.replace("{TaskResult}", "从" + optionInfo.TaskPState 
				+ optionInfo.TaskOption + "到" + optionInfo.TaskState); // 任务处理结果
		
		// 系统通知
		if(!StringUtils.IsNullOrSpace(configTaskRow.getNoticeXt())
				&& configTaskRow.getNoticeXt().equals("1")){
			if(getSystemNotice()!=null){
				getSystemNotice().sendNotice(null, to, "系统通知", body);
			}
		}
		
		// EMail通知
		if(!StringUtils.IsNullOrSpace(configTaskRow.getNoticeEMail())
				&& configTaskRow.getNoticeEMail().equals("1")){
			if(getEmailNotice()!=null){
				getEmailNotice().sendNotice(null, to, "系统通知", body);
			}
		}
		
		// 电话通知
		if(!StringUtils.IsNullOrSpace(configTaskRow.getNoticePhone())
				&& configTaskRow.getNoticePhone().equals("1")){
			if(getPhoneNotice()!=null){
				getPhoneNotice().sendNotice(null, to, "系统通知", body);
			}
		}
	}
}